package cn.zjj.exception;

import cn.zjj.enums.GlobalErrorCode;
import cn.zjj.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalException {


    @ExceptionHandler(Exception.class)
    public JsonResult globleException(Exception e){
        e.printStackTrace();
        log.info("发生exception异常"+e.getMessage());
        return JsonResult.error(GlobalErrorCode.SERVICE_ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JsonResult globalCustomException(GlobalCustomException e){
        e.printStackTrace();
        log.info("发生globalCustomException异常");
        return JsonResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class) //JSR303标准中Bean validation的异常类型,domain参数异常
    public JsonResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder str = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(item->
                str.append(item.getDefaultMessage()).append("  ")
        );
        log.info("参数校验异常"+str.toString());
        return JsonResult.error(str.toString(),"10000");
    }

}
